#include "logwindow.h"
#include "ui_logwindow.h"

#include <QDesktopServices>
#include <QFileDialog>
#include <QMessageBox>
#include <QTableWidgetItem>
#include <QUrl>
#include<QAxObject>
#include<QDate>
#include <QMenu>
#include <QPrinter>
#include <QPainter>
#include <QPrintPreviewDialog>
LogWindow::LogWindow(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::LogWindow)
{
    ui->setupUi(this);
    setHeader();
    RightMenu();
    //获取当前时间
    QDateTime time = QDateTime::currentDateTime();
    QString dateTime = time.toString("yyyy-MM-dd");
    //当前时间的文件
    QString str= QString("Data_%1.xml").arg(dateTime);
    QString str_=QString("Data1_%1.xml").arg(dateTime);
    //获取当前时间前一天时间
    QString firstBeforeDay=time.addDays(-1).toString("yyyy-MM-dd");
    QString str1=QString("Data_%1.xml").arg(firstBeforeDay);
    QString str1_=QString("Data1_%1.xml").arg(firstBeforeDay);
    //获取当前时间前2天时间
    QString secondBeforeDay=time.addDays(-2).toString("yyyy-MM-dd");
    QString str2=QString("Data_%1.xml").arg(secondBeforeDay);
    QString str2_=QString("Data1_%1.xml").arg(secondBeforeDay);
    //获取当前时间前3天时间
    QString threeBeforeDay=time.addDays(-3).toString("yyyy-MM-dd");
    QString str3=QString("Data_%1.xml").arg(threeBeforeDay);
    QString str3_=QString("Data1_%1.xml").arg(threeBeforeDay);
    readXml(str);
    readXml(str_);
    readXml(str1);
    readXml(str1_);
    readXml(str2);
    readXml(str2_);
    readXml(str3);
    readXml(str3_);
    DelLog();
}

LogWindow::~LogWindow()
{
    delete ui;
}
void LogWindow::RightMenu()
{
    //创建菜单
    QMenu* menu= new QMenu();
    QAction* m_printAction = new QAction(menu);//打印
    QAction* m_previewAction = new QAction(menu);//预览
    QAction* m_pdfAction = new QAction(menu);//pdf

    m_printAction->setText("打印");
    m_previewAction->setText("预览");
    m_pdfAction->setText("pdf");
    //将按钮添加到菜单
    menu->addAction(m_printAction);
    menu->addAction(m_previewAction);
    menu->addAction(m_pdfAction);
    ui->pushButton_print->setMenu(menu);
    //实现打印
    connect(m_printAction, SIGNAL(triggered()),this, SLOT(PrintClicked()));
    //打印预览功能
    connect(m_previewAction, SIGNAL(triggered()),this, SLOT(PreviewClicked()));
    //转成pdf
    connect(m_pdfAction, SIGNAL(triggered()),this, SLOT(PdfClicked()));

}

//设置表头
void LogWindow::setHeader()
{
    QStringList strHeader;
    //表头列表
    strHeader<<"站点名称"<<"所属区域"<<"设备ID"<<"事件类别"<<"事件描述"<<"发生时间"<<"操作员";
    //列数设置为与strHeader的行数相等
    ui->tableWidget_Log->setColumnCount(strHeader.count());
    //将表头插入表中
    for(int i=0;i<ui->tableWidget_Log->columnCount();i++)
    {
        QTableWidgetItem *headerItem;
        headerItem = new QTableWidgetItem(strHeader.at(i));
        ui->tableWidget_Log->setHorizontalHeaderItem(i,headerItem);
    }
    //隔行变色
    ui->tableWidget_Log->setAlternatingRowColors(true);
    //设置表头字体
    ui->tableWidget_Log->horizontalHeader()->setStyleSheet("QHeaderView::section{font:13pt; font-family:黑体;};");
}

void LogWindow::DelLog()
{
    QDir dir;
    dir.setFilter(QDir::Files | QDir::NoSymLinks);//列出文件,不列出符号链接
    dir.setSorting(QDir::Time | QDir::Reversed);//按文件时间排序,相反的排序顺序

    QFileInfoList list = dir.entryInfoList();
    for (int i = 0; i < list.size(); ++i)
    {
        QString suffix = list[i].suffix();//获取后缀名
        if (suffix.compare("xml") == 0)//如果后缀为"xml"
        {
        QFileInfo fileInfo = list.at(i);
        qDebug() << qPrintable(QString("%1").arg(fileInfo.fileName()));
        }
    }
}
void LogWindow::readXml(QString str)
{
    QFile m_file(str);
    if (!m_file.open(QIODevice::ReadOnly))
    {
        qDebug()<<"read open false";
        return;
    }
    QDomDocument doc;
    if(!doc.setContent(&m_file))
    {
        m_file.close();
        qDebug()<<"read open xml false";
        return;
    }
    qDebug()<<"read open xml true";

    //读取根节点
    QDomElement root = doc.documentElement();
    //读取第一个父节点
    QDomNode node = root.firstChild();
    while(!node.isNull())
    {
        //读取子结点集合
        QDomNodeList sonList = node.childNodes();
        //读取父节点名字
        QString rootName = node.toElement().tagName();
        if(rootName.compare("data") == 0)
        {
            //将子结点集合传进去读取子结点数据
            readRootXml(sonList);
        }
        //读取下一父节点
        node = node.nextSibling();
    }
}

void LogWindow::readRootXml(QDomNodeList sonNodeList)
{
    int row=ui->tableWidget_Log->rowCount();//表格行数
    ui->tableWidget_Log->insertRow(row);
    for(int sonNode = 0;sonNode < sonNodeList.size();sonNode++)
    {
        //获取子结点
        QDomElement sonElement = sonNodeList.at(sonNode).toElement();
        //与取出子结点进行对比
        if(sonElement.toElement().tagName().compare("SiteName") == 0)
        {
            ui->tableWidget_Log->setItem(row,0,new QTableWidgetItem(sonElement.text()));
        }
        if(sonElement.toElement().tagName().compare("Region") == 0)
        {
            ui->tableWidget_Log->setItem(row,1,new QTableWidgetItem(sonElement.text()));
        }
        if(sonElement.toElement().tagName().compare("DeviceID") == 0)
        {
            ui->tableWidget_Log->setItem(row,2,new QTableWidgetItem(sonElement.text()));
        }
        if(sonElement.toElement().tagName().compare("EventType") == 0)
        {
            ui->tableWidget_Log->setItem(row,3,new QTableWidgetItem(sonElement.text()));
        }
        if(sonElement.toElement().tagName().compare("EventDescription") == 0)
        {
            ui->tableWidget_Log->setItem(row,4,new QTableWidgetItem(sonElement.text()));
        }
        if(sonElement.toElement().tagName().compare("OccurrenceTime") == 0)
        {
            ui->tableWidget_Log->setItem(row,5,new QTableWidgetItem(sonElement.text()));
        }
        if(sonElement.toElement().tagName().compare("Operator") == 0)
        {
            ui->tableWidget_Log->setItem(row,6,new QTableWidgetItem(sonElement.text()));
        }
    }
}

void LogWindow::on_pushButton_leading_out_2_clicked()
{
    //导出
    QTableWidget *tableWidget_Log;
    QString title;
    QAxObject *excel = new QAxObject;
    QString fileName = QFileDialog::getSaveFileName(ui->tableWidget_Log, "保存",                                           QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation), "Excel 文件(*.xls *.xlsx)");


    if(fileName != "")
    {
        if(excel->setControl("ket.Application")) //连接Excel控件
        {
            excel->dynamicCall("SetVisible (bool Visible)","false"); //不显示当前窗体
            excel->setProperty("DisplayAlerts", false); //不显示任何警告消息，如果为true那么在关闭是会出现类似"文件已修改，是否保存"的提示
            QAxObject *workBooks = excel->querySubObject("WorkBooks");//获取工作簿集合
            workBooks->dynamicCall("Add"); //新建一个工作簿
            QAxObject *workBook = excel->querySubObject("ActiveWorkBook"); //获取当前工作簿
            QAxObject *workSheet = workBook->querySubObject("Worksheets(int)", 1); //获取第一个工作表（后面的参数代表的是第几张工作表）

            int colCount = ui->tableWidget_Log->columnCount();
            int rowCount = ui->tableWidget_Log->rowCount();

            QAxObject *cell, *col;

            //标题行
            cell = workSheet->querySubObject("Cells(int, int)", 1, 1);
            cell->dynamicCall("SetValue(const QString&)", title);
            cell->querySubObject("Font")->setProperty("Size", 18);
            //调整行高
            workSheet->querySubObject("Range(const QString&)", "1:1")->setProperty("RowHeight", 30);
            //合并标题行
            QString cellTitle;
            cellTitle.append("A1:");
            cellTitle.append(QChar(colCount - 1 + 'A'));
            cellTitle.append(QString::number(1));
            QAxObject *range = workSheet->querySubObject("Range(const QString&)", cellTitle);
            range->setProperty("WrapText", true);
            range->setProperty("MergeCells", true);
            range->setProperty("HorizontalAlignment", -4108);
            range->setProperty("VertivcalAlignment", -4108);

            //列标题
            for (int i = 0; i < colCount; i++)
            {
                QString columnName;
                columnName.append(QChar(i + 'A'));
                columnName.append(":");
                columnName.append(QChar(i + 'A'));
                col = workSheet->querySubObject("Columns(const QString&)", columnName);
                col->setProperty("ColumnWidth", ui->tableWidget_Log->columnWidth(i)/6);
                cell = workSheet->querySubObject("Cells(int, int)", 2, i+1);
                columnName = ui->tableWidget_Log->horizontalHeaderItem(i)->text();
                cell->dynamicCall("SetValue(const QString&)", columnName);
                cell->querySubObject("Font")->setProperty("Bold", true);
                cell->querySubObject("Interior")->setProperty("Color", QColor(191, 191, 191));
                cell->setProperty("HorizontalAlignment", -4108);
                cell->setProperty("VertivcalAlignment", -4108);
            }

            //处理数据
            for (int i = 0; i < rowCount; i++)
            {
                for (int j = 0; j < colCount; j++)
                {
                    workSheet->querySubObject("Cells(int, int)", i + 3, j + 1)->dynamicCall(
                                "SetValue(const QString&)", ui->tableWidget_Log->item(i, j)? ui->tableWidget_Log->item(i, j)->text():"");
                }
            }

            //画框线
            QString l_range;
            l_range.append("A2:");
            l_range.append(colCount -1 + 'A');
            l_range.append(QString::number(ui->tableWidget_Log->rowCount() + 2));
            range = workSheet->querySubObject("Range(const QString&)", l_range);
            range->querySubObject("Borders")->setProperty("LineStyle", QString::number(1));
            range->querySubObject("Borders")->setProperty("Color", QColor(0, 0, 0));

            //调整数据区行高
            QString rowsName;
            rowsName.append("2:");
            rowsName.append(QString::number(ui->tableWidget_Log->rowCount() + 2));
            range = workSheet->querySubObject("Range(const QString&)", rowsName);
            range->setProperty("RowHeight", 20);
            workBook->dynamicCall("SaveAs(const QString&)", QDir::toNativeSeparators(fileName)); //保存到fileName

            workBook->dynamicCall("Close()"); //关闭工作簿
            excel->dynamicCall("Quit()"); //关闭excel
            delete  excel;
            excel = NULL;
            if ((QMessageBox::question(NULL, tr("完成"), tr("文件已导出，是否现在打开？")), QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes)
            {
                QDesktopServices().openUrl(QUrl("file:///" + QDir::toNativeSeparators(fileName)));
            }
        }
        else
        {
            QMessageBox::warning(NULL, tr("错误"), tr("未能创建 Excel 对象，请安装 Microsoft Excel。"), QMessageBox::Apply);
        }

    }
}

void LogWindow::on_pushButton_print_clicked()
{

}

void LogWindow::PrintClicked()
{
    QPrinter printerPixmap;
    QPixmap pixmap = QPixmap::grabWidget(ui->tableWidget_Log, ui->tableWidget_Log->rect());  //获取界面的图片
    printerPixmap.setOrientation(QPrinter::Landscape);//纵向：Portrait 横向：Landscape
    printerPixmap.setPageSize(QPrinter::A4);//设置纸张大小
    QPainter painterPixmap;
    painterPixmap.begin(&printerPixmap);
    painterPixmap.scale(1, 1);//设置图像长宽是原图的多少倍
    painterPixmap.drawPixmap(300, 300 , pixmap);//设置图像在A4中的开始坐标是什么
    painterPixmap.end();
}

void LogWindow::PreviewClicked()
{
    QPrinter printer(QPrinter::HighResolution);
    //自定义纸张大小
    printer.setPageSize(QPrinter::Custom);
    printer.setPaperSize(QSizeF(ui->tableWidget_Log->height(), ui->tableWidget_Log->width()),
                         QPrinter::Point);
    QPrintPreviewDialog preview(&printer, this);
    preview.setMinimumSize(1000,600);
    connect(&preview, SIGNAL(paintRequested(QPrinter*)), SLOT(printPreviewSlot(QPrinter*)));
    preview.exec ();
}

void LogWindow::PdfClicked()
{
    QString fileName = QFileDialog::getSaveFileName(this, tr("保存PDF文件"), QString(), "*.pdf");
    if (!fileName.isEmpty())
    {
        // 如果文件后缀为空，则默认使用.pdf
        if (QFileInfo(fileName).suffix().isEmpty())
        {
            fileName.append(".pdf");
        }
        QPrinter printerPixmap(QPrinter::HighResolution);
        //自定义纸张大小，这里要打印的内容都在stackedWidget上
        printerPixmap.setPageSize(QPrinter::Custom);
        printerPixmap.setPaperSize(QSizeF(ui->tableWidget_Log->height(), ui->tableWidget_Log->width()), QPrinter::Point);
        //设置纸张大小为A4，这里注释掉了，建议自定义纸张 ，否则保存的就会有很多空白
        //printerPixmap.setPageSize(QPrinter::A4);
        //横向打印
        printerPixmap.setOrientation(QPrinter::Landscape);
        //设置输出格式为pdf
        printerPixmap.setOutputFormat(QPrinter::PdfFormat);
        //设置输出路径
        printerPixmap.setOutputFileName(fileName);
        //获取界面的图片
        QPixmap pixmap = QPixmap::grabWidget(ui->tableWidget_Log, ui->tableWidget_Log->rect());

        QPainter painterPixmap;
        painterPixmap.begin(&printerPixmap);
        QRect rect = painterPixmap.viewport();
        int x = rect.width() / pixmap.width();
        int y = rect.height() / pixmap.height();
        //将图像(所有要画的东西)在pdf上按比例尺缩放,如果想展示原始图，就讲x和y设置为1就可以了
        painterPixmap.scale(x, y);
        //画图
        painterPixmap.drawPixmap(0, 0, pixmap);
        painterPixmap.end();

        QMessageBox::information(this, tr("生成PDF"), tr("保存PDF文件成功"), QMessageBox::Ok);
    }
}
void LogWindow::printPreviewSlot(QPrinter* printerPixmap)
{
    printerPixmap->setOrientation(QPrinter::Landscape);
    //获取界面的图片
    QPixmap pixmap = QPixmap::grabWidget(ui->tableWidget_Log, ui->tableWidget_Log->rect());
    QPainter painterPixmap(this);
    painterPixmap.begin(printerPixmap);
    QRect rect = painterPixmap.viewport();
    int x = rect.width() / pixmap.width();
    int y = rect.height() / pixmap.height();
    painterPixmap.scale(x, y);
    painterPixmap.drawPixmap(0, 0, pixmap);
    painterPixmap.end();
}
